﻿using Microsoft.EntityFrameworkCore;
using MiniFox.Components;
using MiniFox.Data.EntityFramework;
using MiniFox.Utility;
using TemplateEngine.Models;
using TemplateEngine.Providers;

namespace Sys.Data
{
    [AutoResolve]
    public class TemplateProvider : EntityDataProvider<PlatformDbContext>, ITemplateDataProvider
    {
        const string REPO_NAME = "dispatcher";
        public TemplateDo GetTemplate(string name)
        {
            var versionSet = this.CurrentDbContext.VersionSet.SingleOrDefault(t => t.RepoName == REPO_NAME && t.Name == name);
            if (versionSet == null)
                return null;

            if (versionSet.PubId == null)
                return null;

            var publish = this.CurrentDbContext.PublishLog.SingleOrDefault(p => p.Id == versionSet.PubId);

            if (publish == null)
                return null;

            var versionItem = this.CurrentDbContext.VersionItem.SingleOrDefault(v => v.Id == publish.VersionId);
            if (versionItem == null)
                return null;
            dynamic template = versionItem.Content.ToJsonObject();
            return new TemplateDo
            {
                Name = name,
                DisplayName = template.displayName,
                Content = template.bodyContent
            };
        }

        public async Task<TemplateDo> GetTemplateAsync(string name)
        {
            var versionSet = await this.CurrentDbContext.VersionSet.SingleOrDefaultAsync(t => t.RepoName == REPO_NAME && t.Name == name);
            if (versionSet == null)
                return null;

            if (versionSet.PubId == null)
                return null;

            var publish = await this.CurrentDbContext.PublishLog.SingleOrDefaultAsync(p => p.Id == versionSet.PubId);

            if (publish == null)
                return null;

            var versionItem = await this.CurrentDbContext.VersionItem.SingleOrDefaultAsync(v => v.Id == publish.VersionId);
            if (versionItem == null)
                return null;
            dynamic template = versionItem.Content.ToJsonObject();
            return new TemplateDo
            {
                Name = name,
                DisplayName = template.displayName,
                Content = template.bodyContent
            };
        }
    }
}
